import path from 'path';
import fs from 'fs-extra';
import dotenv from 'dotenv';
import { getCommentByPath } from './yaml-util.js';
import { parse as parseYaml } from 'yaml';

// 加载配置
class Config {
  constructor() {
    this.rootDir = this.findRootDir();
    this.loadEnv();
    this.loadPackageJson();
    this.loadScriptsConfig();
  }

  findRootDir() {
    let dir = process.cwd();
    while (dir !== path.dirname(dir)) {
      if (fs.existsSync(path.join(dir, 'pnpm-workspace.yaml'))) {
        return dir;
      }
      dir = path.dirname(dir);
    }
    throw new Error('Could not find monorepo root (pnpm-workspace.yaml)');
  }

  loadEnv() {
    const envPath = path.join(this.rootDir, '.scripts/.env');
    if (fs.existsSync(envPath)) {
      dotenv.config({ path: envPath, silent: true });
    }
  }

  loadPackageJson() {
    this.packagePath = path.join(this.rootDir, 'package.json');
    this.packageJson = JSON.parse(fs.readFileSync(this.packagePath, 'utf8'));
  }

  get(key, defaultValue) {
    return process.env[key] || defaultValue;
  }

  loadScriptsConfig() {
    try {
      this.yamlPath = path.join(this.rootDir, '.scripts/scripts.yaml');
      this.yamlContent = fs.readFileSync(this.yamlPath, 'utf8');
      const data = parseYaml(this.yamlContent);
      this.yamlConfig = data.scripts || {};
    } catch (e) {
      throw new Error('无法加载 scripts.yaml', e.message);
    }
  }

  /**
   * 获取 YAML 文档中指定路径的注释信息（增强版）
   * @param {string[]} path - 键的路径
   * @returns {object|null} 包含注释信息的对象
   *
   * @example
   * // 方式1: 使用数组路径（推荐用于包含特殊字符的键名）
   * getComment(['scripts', 'conf:help', 'examples', 'pnpm help build']);
   */
  getComment(path) {
    return getCommentByPath(this.yamlContent, path);
  }
}

export default new Config();
